package com.timothy.activity;

import com.timothy.service.LocalService;
import com.timothy.service.LocalService.LocalBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ServiceDemoActivity extends Activity {
	LocalService mService;
    boolean mBound = false;
    Button testBtn = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	Log.i("ServiceDemo", "ServiceDemoActivity.onCreate()...");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        testBtn = (Button) this.findViewById(R.id.testBtn);
        testBtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				onButtonClick(v);
			}
		});
    }

    @Override
    protected void onStart() {
    	Log.i("ServiceDemo", "ServiceDemoActivity.onStart()...");
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
    	Log.i("ServiceDemo", "ServiceDemoActivity.onStop()...");
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    /** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */
    public void onButtonClick(View v) {
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            int num = mService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
        	Log.i("ServiceDemo", "ServiceDemoActivity.ServiceConnection.onServiceConnected()...");
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        	Log.i("ServiceDemo", "ServiceDemoActivity.onServiceDisconnected()...");
            mBound = false;
        }
    };
}